"""
    Author:
    Date: 2018-11-01

    GM管理类
"""

from django.contrib.auth.models import User

from utils import db


# 用户权限定义
PERMISSION_GM_MANAGEMENT            = 1  # GM管理
PERMISSION_SYSTEM_CONFIG            = 2  # 系统配置
PERMISSION_SERVER_STATUS            = 3  # 服务器状态
PERMISSION_RECHARGE_MANAGEMENT      = 4  # 充值管理
PERMISSION_BROADCASTER_AUTH         = 5  # 主播审核
PERMISSION_BROADCASTER_MANAGEMENT   = 6  # 主播管理
PERMISSION_REVIEW                   = 7  # 复查权限
PERMISSION_AGENT_MANAGEMENT         = 8  # 代理管理
PERMISSION_WITHDRAW_MANAGEMENT      = 9  # 提现管理
PERMISSION_CAST_MONITOR             = 10  # 直播监控
PERMISSION_DATA_STAT                = 11  # 数值统计
PERMISSION_VIDEO_AUTH               = 12  # 视频审核
PERMISSION_PHOTO_AUTH               = 13  # 照片审核
PERMISSION_ADD_DIAMOND              = 14  # 增加钻石
PERMISSION_SET_CAST_PRICE           = 15  # 设置直播价格
PERMISSION_GUILD_MANAGEMENT         = 16  # 公会管理
PERMISSION_COMPLAINT_MANAGEMENT     = 17  # 举报管理
PERMISSION_VIEW_VIDEO_LOG           = 18  # 视频录制回放
PERMISSION_HOMEPAGE_REPORT          = 19  # 简报功能
PERMISSION_FAKE_DETECT              = 20  # 用户行为分析
PERMISSION_RADIO_MANAGEMENT         = 21  # 消息广播
PERMISSION_USER_LIST                = 22  # 用户表单
PERMISSION_SET_SHARE_BONUS_RATIO    = 23  # 设置分享提成比例
PERMISSION_VIEW_PRIVATE_MESSAGE     = 24  # 查看用户私信内容
PERMISSION_MARKET_MANAGEMENT        = 25  # 市场营销
PERMISSION_APP_MANAGEMENT           = 26  # 产品管理
PERMISSION_CUSTOMER_SERVICE         = 27  # 客服服务
PERMISSION_AB_TEST                  = 28  # AB测试
PERMISSION_MOMENT_AUTH              = 29  # 动态审核
PERMISSION_ASSESS                   = 30  # 考核指标
PERMISSION_REFUND                   = 31  # 通话退款
PERMISSION_SECURITY                 = 32  # 安全模块

PERMISSION_META_DATA = {
    PERMISSION_GM_MANAGEMENT:           {'name': '🍩 GM管理',        'key': 'gm_management'},
    PERMISSION_SYSTEM_CONFIG:           {'name': '🛠 系统配置',      'key': 'system_config'},
    PERMISSION_SERVER_STATUS:           {'name': '📺 服务监控',      'key': 'server_status'},
    PERMISSION_RECHARGE_MANAGEMENT:     {'name': '💵 充值管理',      'key': 'recharge_management'},
    PERMISSION_BROADCASTER_AUTH:        {'name': '👑 主播审核',      'key': 'broadcaster_auth'},
    PERMISSION_BROADCASTER_MANAGEMENT:  {'name': '👑 主播管理',      'key': 'broadcaster_management'},
    PERMISSION_REVIEW:                  {'name': '👓 复查管理',      'key': 'review'},
    PERMISSION_AGENT_MANAGEMENT:        {'name': '🤵 代理管理',      'key': 'agent_management'},
    PERMISSION_WITHDRAW_MANAGEMENT:     {'name': '💸 提现管理',      'key': 'withdraw_management'},
    PERMISSION_CAST_MONITOR:            {'name': '📺 直播监控',      'key': 'cast_monitor'},
    PERMISSION_DATA_STAT:               {'name': '📦 数值统计',      'key': 'data_stat'},
    PERMISSION_VIDEO_AUTH:              {'name': '🎞 视频审核',      'key': 'video_auth'},
    PERMISSION_PHOTO_AUTH:              {'name': '🌠 照片审核',      'key': 'photo_auth'},
    PERMISSION_ADD_DIAMOND:             {'name': '💎 增加钻石',      'key': 'add_diamond'},
    PERMISSION_SET_CAST_PRICE:          {'name': '💰 直播价格',      'key': 'set_cast_price'},
    PERMISSION_GUILD_MANAGEMENT:        {'name': '🏛 公会管理',      'key': 'guild_management'},
    PERMISSION_COMPLAINT_MANAGEMENT:    {'name': '📪 举报管理',      'key': 'complaint_management'},
    PERMISSION_HOMEPAGE_REPORT:         {'name': '📋 首页简报',      'key': 'homepage_report'},
    PERMISSION_FAKE_DETECT:             {'name': '🚷 用户行为',      'key': 'fake_detect'},
    PERMISSION_RADIO_MANAGEMENT:        {'name': '📻 消息广播',      'key': 'radio_management'},
    PERMISSION_USER_LIST:               {'name': '🐳 用户表单',      'key': 'user_list'},
    PERMISSION_SET_SHARE_BONUS_RATIO:   {'name': '🎈 分享提成',      'key': 'set_share_bonus_ratio'},
    PERMISSION_VIEW_PRIVATE_MESSAGE:    {'name': '💌 查看私信',      'key': 'view_private_message'},
    PERMISSION_MARKET_MANAGEMENT:       {'name': '📈️ 市场营销',      'key': 'market_management'},
    PERMISSION_APP_MANAGEMENT:          {'name': '🌽 产品管理',      'key': 'app_management'},
    PERMISSION_CUSTOMER_SERVICE:        {'name': '☎ 客户服务',      'key': 'customer_service'},
    PERMISSION_AB_TEST:                 {'name': '🌓 AB测试',       'key': 'ab_test'},
    PERMISSION_MOMENT_AUTH:             {'name': '📷 动态审核',      'key': 'moment_auth'},
    PERMISSION_VIEW_VIDEO_LOG:          {'name': '👓 视频回放',      'key': 'view_video_log'},
    PERMISSION_ASSESS:                  {'name': '🏆 考核指标',      'key': 'assess'},
    PERMISSION_REFUND:                  {'name': '💰 通话退款',      'key': 'refund'},
    PERMISSION_SECURITY:                {'name': '👮‍ 安全管理',      'key': 'security'},
}


def has_permission_for_openid(openid, permission_id):
    """ 判断请求用户是否有指定的权限 """
    user = get_gm_detail_by_openid(openid)
    if user is None:
        return False

    return has_permission(user['permission'], permission_id)


def get_gm_level_desp(level):
    """ 获取用户gm等级的描述 """
    level_desp_data = {
        0: '普通用户',
        1: '普通用户',
        2: '管理员',
        3: '高级管理员',
        9: '系统管理员',
    }
    return level_desp_data.get(level, '???')


def get_gm_permission_name(pid):
    """ 获取GM权限的名称 """
    return PERMISSION_META_DATA.get(pid, {'name': '??'})['name']


def has_permission(permission, permission_id):
    """ 判断是否有某个权限 """
    return permission & (1 << permission_id - 1) > 0


def get_gm_permission_detail(permission):
    """ 获取GM的权限详情 """
    permission_detail = {}
    for k, v in PERMISSION_META_DATA.items():
        key = v['key']
        permission_detail[key] = {
            'pid': k,
            'name': get_gm_permission_name(k),
            'open': has_permission(permission, k),
        }
    return permission_detail


def get_gm_list(count):
    """ 列表 """
    sql = f'''
        SELECT      *
        FROM        gma_profile
        ORDER BY    level DESC
        LIMIT       {count};
    '''
    data = db.query_data_from_db(sql)
    return [] if data is None else data


def get_gm_count():
    """ 获取GM用户的数量 """
    sql = f'''
        SELECT      COUNT(*) AS count
        FROM        gma_profile;
    '''
    data = db.query_data_from_db(sql)
    if data is None:
        return 0
    return data[0]['count']


def get_gm_detail_by_openid(openid):
    """ 获取GM的详情 """
    sql = f'''
        SELECT      *
        FROM        gma_profile
        WHERE       openid="{openid}"
        LIMIT       1;
    '''
    data = db.query_data_from_db(sql)
    return data[0] if data else None


def get_gm_detail_by_mobile(mobile):
    """ 根据mobile获取GM的详情 """
    if mobile is None:
        return None

    sql = f'''
        SELECT      *
        FROM        gma_profile
        WHERE       mobile="{mobile}"
        LIMIT       1;
    '''
    data = db.query_data_from_db(sql)
    return data[0] if data else None


def get_gm_detail(uid):
    """ 获取GM的详情 """
    sql = f'''
        SELECT      *
        FROM        gma_profile
        WHERE       user_id={uid}
        LIMIT       1;
    '''
    data = db.query_data_from_db(sql)
    return data[0] if data else None


def set_gm_level(uid, level):
    """ 设置GM等级 """
    sql = f'''
        UPDATE      gma_profile
        SET         level={level}
        WHERE       user_id={uid}
        LIMIT       1;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows == 1


def set_gm_permission(uid, permission):
    """ 设置GM等级 """
    sql = f'''
        UPDATE      gma_profile
        SET         permission={permission}
        WHERE       user_id={uid}
        LIMIT       1;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows == 1


def is_gm_exists(username):
    """ 判断GM是否存在 """
    try:
        user = User.objects.get(username=username)
    except Exception:
        user = None
    return user is not None


def get_gm_by_mobile(mobile):
    """ 根据手机号码查找gm """
    openid = get_gm_openid_by_mobile(mobile)
    if openid is None:
        return None

    return get_gm(openid)


def get_gm_openid_by_mobile(mobile):
    """ 根据mobile查找gm的openid """
    sql = '''
        SELECT      *
        FROM        gma_profile
        WHERE       mobile=%(mobile)s;
    '''
    params = {
        'mobile': mobile,
    }
    data = db.query_data_from_db(sql, params)
    return data[0]['openid'] if data else None


def get_gm(username):
    """ 获取gm详细信息 """
    if not username:
        return None

    try:
        user = User.objects.get(username=username)
    except Exception:
        user = None
    return user


def create_gm(username, user_profile):
    """ 创建新的GM """
    try:
        user = User.objects.create_user(username=username, email='', password='')
    except Exception:
        return None

    user.profile.openid = user_profile['openid']
    user.profile.unionid = user_profile['unionid']
    user.profile.nickname = user_profile['nickname']
    user.profile.avatar = user_profile['headimgurl']
    user.profile.gender = user_profile['sex']
    user.profile.country = user_profile['country']
    user.profile.province = user_profile['province']
    user.profile.city = user_profile['city']
    user.save()

    return user


def delete_gm(uid):
    """ 删除GM """
    try:
        user = User.objects.get(id=uid)
        user.delete()
    except Exception:
        return False
    return True


def get_gm_id(openid):
    """ 获取pass """
    gm = get_gm_detail_by_openid(openid)
    return gm['id'] if gm else 0


def get_gm_apps(gm_id):
    """ 获取gm管理的app列表 """
    sql = f'''
        SELECT      *
        FROM        gma_app
        WHERE       gm_id={gm_id} AND
                    enable=1;
    '''
    data = db.query_data_from_db(sql)
    return [x['app_bundle_id'] for x in data] if data else []


def get_gm_guilds(gm_id):
    """ 获取gm管理的公会列表 """
    sql = f'''
        SELECT      *
        FROM        gma_guild
        WHERE       gm_id={gm_id} AND
                    enable=1;
    '''
    data = db.query_data_from_db(sql)
    return [x['guild_id'] for x in data] if data else []


def create_guild(gm_id, guild_id):
    """ 创建公会 """
    sql = f'''
        INSERT INTO gma_guild
        SET         gm_id={gm_id},
                    guild_id={guild_id},
                    enable=1;
    '''
    affected_rows = db.execute_sql(sql)
    return affected_rows == 1


if __name__ == '__main__':
    print('ok')
